package com.congee02.dbservlet.service.update;

import com.congee02.dbservlet.dao.UserDao;
import com.congee02.dbservlet.db.SingletonJdbcTemplate;
import com.congee02.dbservlet.entity.User;
import com.congee02.dbservlet.framework.ioc.annotation.Autowired;
import com.congee02.dbservlet.framework.ioc.annotation.Component;
import com.congee02.dbservlet.framework.jdbc.JdbcTemplate;
import com.congee02.dbservlet.result.Result;
import com.congee02.dbservlet.result.ResultFactory;
import com.congee02.dbservlet.utils.StringValidationUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@Component("updateService")
public class UpdateServiceImpl implements UpdateService {

    @Autowired
    private UserDao userDao;

    @Override
    public Result<?> updatePassword(String username, String oldPassword, String newPassword) {
        if (StringValidationUtils.isAnyNullOrBlank(username, oldPassword, newPassword)) {
            return ResultFactory.failedResult("请将所有信息填写完整。");
        }
        JdbcTemplate template = SingletonJdbcTemplate.get();
        try {
            if (! userDao.isUserExist(username, oldPassword, template)) {
                return ResultFactory.failedResult("当前用户不存在或者旧密码不匹配");
            }
        } catch (SQLException ignored) {
            return ResultFactory.failedResult("数据库错误，更新失败。");
        }

        boolean updateSuccess = true;
        try {
            User entity = new User();
            entity.setPwd(newPassword);
            User condition = new User();
            condition.setPwd(oldPassword);
            condition.setUsername(username);
            int affectedRows = userDao.update(entity, condition);
            if (affectedRows < 1) {
                updateSuccess = false;
            }
        } catch (SQLException ignored) {
            updateSuccess = false;
        }
        if (! updateSuccess) {
            return ResultFactory.failedResult("数据库错误，更新失败。");
        } else {
            return ResultFactory.successResult("更新密码成功");
        }
    }
}
